from django.template import Library
from django.conf import settings
import re

# 有序字典
from collections import OrderedDict

register = Library()


@register.inclusion_tag('rbac/menu.html')
def menu(request):
    '''菜单'''
    menu_dict = request.session.get(settings.MENU_LIST)
    # 实例化对象
    ordered_dict = OrderedDict()

    for key in sorted(menu_dict):
        ordered_dict[key] = menu_dict[key]
        menu_dict[key]['class'] = 'hide'
        # 循环儿子，添加相应的
        for node in menu_dict[key]['children']:

            # 当前存session的权限列表中的，二级/三级菜单id，跟菜单列表中的二级菜单的id对应上，默认选中
            if request.current_menu_id == node['id']:
                # 给儿子展开
                node['class'] = 'active'
                # 给父亲添加展开
                menu_dict[key]['class'] = ''

    return {'menu_dict': ordered_dict}


@register.inclusion_tag('rbac/breadcrumb.html')
def breadcrumb(request):
    '''导航'''
    return {'breadcrumb_list': request.breadcrumb_list}


@register.filter
def has_permissions(request, name):
    permissions_dict = request.session.get(settings.PERMISSIONS_LIST)

    if name in permissions_dict:
        return True
